import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import facilityApi from "@/api/facilityApi.ts";
import {Facility} from "@/types/resp/facility";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";

interface FacilityAddProps {
  visible: boolean;
  id: number;
  onCloseFacilityAdd: () => void;
}

const FacilityAdd: React.FC<FacilityAddProps> = ({visible, id, onCloseFacilityAdd}) => {

  const [form] = Form.useForm<Facility>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
  };

  let facilityForm: Partial<Facility> = {}

  const [title, setTitle] = useState('新增公共设施信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑公共设施信息')
      initFacilityFormById(id)
    } else {
      setTitle('新增公共设施信息')
      form.resetFields();
    }
  }, [visible]);

  const initFacilityFormById = async (id: number) => {
    const resp: Result<Facility> = await facilityApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      facilityForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let facility2Save:Facility = form.getFieldsValue()
      if (id) {
        facility2Save = Object.assign(facilityForm, facility2Save)
      }
      const resp: Result<void> = await facilityApi.save(facility2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增公共设施信息')
    form.resetFields();
  };
  
  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };

  const onBack = () => {
    onCloseFacilityAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseFacilityAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="facilityForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="name" label="公共设施名称">
              <Input maxLength={255} placeholder="请输入公共设施名称"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="buildingName" label="楼栋名称" rules={rules.buildingName}>
              <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="location" label="位置">
              <Input maxLength={255} placeholder="请输入位置"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="lastMaintenanceDate" label="最后保养日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择状态" options={[
                { value: 10, label: <span>正常</span> },
                { value: 20, label: <span>异常</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
    </Modal>
  )
}

export default FacilityAdd;
